<?php

namespace app\common\shop;

use app\common\entity\Config;
use app\common\entity\MywalletLog;
use app\common\entity\User;
use think\Db;
use think\Model;
use think\model\concern\SoftDelete;

// 会员等级
class UserLevelModel extends model {
     /**
     * [注册直推奖励]
     * @param 
     * @return
     */
    public static function reg( $uid,$pid ){
        $register_recommend_bless = Config::getValue('register_recommend_bless');
        if($register_recommend_bless >=0 && $pid >0){
            // 赠送福币
            MywalletLog::addLog($pid, $register_recommend_bless, '1', '直推注册', 10, 1);
        } 
        $register_money = Config::getValue('register_money');
        if($register_money > 0 && $uid){
            // 余额
            MywalletLog::addLog($uid, $register_money, '4', '注册赠送', 11, 1);
        }
        self::level($uid);//2021-1-15升级
        return [$uid,$pid];
    }

    /**
     * [计算奖励]
     * 【三级分销】
     * [增加业绩-个人业绩-团队业绩]
     * @param $order 订单信息
     * @return
     */
    public static function commssion( $order ){
        if($order['shoptype'] == 2){
            // 代金券商城商品没有奖励
            return '代金券商城商品没有奖励';
        }
        /*2021-1-28 购物奖励重复 */
        if($order['overcommssion'] == 1){
            return '已经计算过奖励';
        }
        OrderModel::where('id',$order['id'])->setField('overcommssion',1);
        /* end 2021-1-28 购物奖励重复 */
        $uid = $order['uid'];// 购买商品会员id
        $user = self::getUser($uid);
        $number = $order['total'];
        // 增加个人业绩
        self::addselfperformance($uid,$number);
        if($user['pid']){
            // 上级的团队业绩
            self::addteamperformance($uid,$number);
        }
        self::level($order['uid']);//2021-1-15 升级
        // 三级购物返
        if($user['pid']){
            // 一级购物返比例
            $shop_return_one = Config::getValue('shop_return_one');
            $onePuser = self::getUser($user['pid']);
            if($onePuser){
                //一级得到的奖励
                $oneNumber = $order['total'] * $shop_return_one/100;
                if($oneNumber > 0){
                    // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                    MywalletLog::addLog($onePuser['id'],$oneNumber,4,'一级购物奖励',4,1,$uid);
                }
                if($onePuser['pid']){
                    // 二级购物返比例
                    $shop_return_two = Config::getValue('shop_return_two');
                    $twoPuser = self::getUser($onePuser['pid']);
                    if($twoPuser){
                        //一级得到的奖励
                        $twoNumber = $order['total'] * $shop_return_two/100;
                        if($twoNumber > 0){
                            // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                            MywalletLog::addLog($twoPuser['id'],$twoNumber,4,'二级购物奖励',4,1,$uid);
                        }
                    }
                    if($twoPuser['pid']){
                        // 三级购物返比例
                        $shop_return_three = Config::getValue('shop_return_three');
                        $threePuser = self::getUser($twoPuser['pid']);
                        if($threePuser){
                            //一级得到的奖励
                            $threeNumber = $order['total'] * $shop_return_three/100;
                            if($threeNumber > 0){
                                // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                                MywalletLog::addLog($threePuser['id'],$threeNumber,4,'三级购物奖励',4,1,$uid);
                            }
                        }
                    }
                }
            }
        }
        self::area($order);

        //2021-1-15 改团长奖实时
        self::teamCommission($user['pid'],$order);
    }
   /**
     * [区域代理奖]
     * @param
     * @return
     */
    public static function area( $order ){
        file_put_contents(dirname(__FILE__).'/order',json_encode($order));
        $address = unserialize($order['address_date']);
        $province = $address['province'];
        $orderuser = User::where('id',$order['uid'])->find();
        $city = $address['city'];
        $area = $address['area'];
        // 区代理
        $area_level_area = User::where('area_level',1)->where('province',$province)->where('city',$city)->where('area',$area)->where('area_over_time','>',time())->find();
        if(!empty($area_level_area)){
            // 有区代理
            $level = UserAreaLevelModel::where('id',1)->find();
            if($orderuser['pid'] == $area_level_area['id']){
                // 属于直推
                $percentage = $level['selfpercentage'];
                $t = '直推';
            }else{
                $percentage = $level['percentage'];
                $t = '';
            }
            $area_money = $order['total'] * $percentage/100;
            if($area_money > 0){
                // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                MywalletLog::addLog($area_level_area['id'],$area_money,4,$t.'区代理',9,1,$orderuser['id']);
            }
        }
        // 市代理
        $area_level_city = User::where('area_level',2)->where('province',$province)->where('city',$city)->where('area_over_time','>',time())->find();
        if(!empty($area_level_city)){
            // 有市代理
            $level_city = UserAreaLevelModel::where('id',2)->find();
            if($orderuser['pid'] == $area_level_city['id']){
                // 属于直推
                $percentage = $level_city['selfpercentage'];
                $t = '直推';
            }else{
                $percentage = $level_city['percentage'];
                $t='';
            }
            $city_money = $order['total'] * $percentage/100;
            if($city_money > 0){
                // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                MywalletLog::addLog($area_level_city['id'],$city_money,4,$t.'市代理',9,1,$orderuser['id']);
            }
        }
        // 省代理
        $area_level_province = User::where('area_level',3)->where('province',$province)->where('area_over_time','>',time())->find();
        file_put_contents(dirname(__FILE__).'/area_level_province',json_encode($area_level_province));

        if(!empty($area_level_province)){
            // 有省代理
            $level_province = UserAreaLevelModel::where('id',3)->find();
            if($orderuser['pid'] == $area_level_province['id']){
                // 属于直推
                $percentage = $level_province['selfpercentage'];
                $t = '直推';
            }else{
                $percentage = $level_province['percentage'];
                $t='';
            }
            $province_money = $order['total'] * $percentage/100;
            file_put_contents(dirname(__FILE__).'/province_money',json_encode($province_money));

            if($province_money > 0){
                // $uid, $number, $wallet_type, $remark, $types, $status,$from=0
                MywalletLog::addLog($area_level_province['id'],$province_money,4,$t.'省代理',9,1,$orderuser['id']);
            }
        }
        return true;
    }

    /**
     * [团长奖]
     * $uid 会员id
     * $order 订单信息
     * $level 上次计算的等级
     *
     * @param
     * @return
     */
    public static function teamCommission($uid,$order,$level=[]){
        $user = User::where('id',$uid)->find();
        if($user['team_level'] ==0) {// 不是团长
            if($user['pid'] == 0) return ;// 已经没有上级
            return self::teamCommission($user['pid'],$order,$level);// 继续找上级
        }
        // 团长设置
        $teamlevel = UserTeamLevelModel::field('id,percentage')->where('id',$user['team_level'])->find();
        $fee = 0;// 比例
        if(empty($level)){
            // 第一次计算奖励
            $fee = $teamlevel['percentage'];
        }elseif($user['team_level'] > $level['id']){
            // 大于下级的等级-可以得到奖励
            $fee = $teamlevel['percentage'] - $level['percentage'];// 级差
        }
        if($fee > 0){
            $money = $order['total'] * $fee/100;// 可以得到的奖励
            if($money >0){
                MywalletLog::addLog($uid, $money, 4, '团长奖', 17, 1);
            }
        }
        if($user['pid'] == 0) return ;// 已经没有上级
        return self::teamCommission($user['pid'],$order,$teamlevel);// 继续找上级
    }
    //团队奖
    static public function team(){
        $date = date('d',time());
        $h = date('H',time());
        if($date != 1){
            #return '每月1号0点释放';
        }
        if($h != 0){
            #return '每月1号0点释放';
        }

        /*$statr_time = strtotime(date('Y-m-01 00:00:00',strtotime('first day of -1 month')));
        $end_time = strtotime(date('Y-m-d 23:59:59',strtotime('last day of -1 month')));*/
        $statr_time = strtotime(date('Y-m-d',strtotime(date('Y-m-01 00:00:00',strtotime('first day of this month')))));
        $end_time = strtotime(date('Y-m-d',strtotime(date('Y-m-d 23:59:59',strtotime('last day of this month')))));
        $users = User::field('id,pid,team_level')->where('team_level','>',0)->select();
            $orders= User::alias('u')
            ->join('shop_order o','o.uid = u.id')
            ->field('u.id,u.pid,u.team_level,sum(o.total) as total')
            ->whereBetweenTime('sendtime',$statr_time,$end_time)
            #->whereTime('sendtime','last month')
            ->where('u.status',1)
            ->where('o.status','in','2,3')
            ->group('u.id')
            ->select();
        /*$model = new User();
        return $model->getLastSql();*/
            $list = [];

            foreach($users as $k=>$v){
                if($v['team_level'] > 0){
                    $team_level = UserTeamLevelModel::where('id',$v['team_level'])->find();
                    $users[$k]['percentage'] = $team_level['percentage'];
                    $users[$k]['peers'] = $team_level['peers'];
                    $item = self::getTeamProfit($orders,$v['id'],$v['team_level'],$team_level['percentage'],$team_level['peers']);
                    $v['list'] = $item;
                    $list[] = $v;
                    $profit = 0;
                    foreach($item as $key=>$val){
                        $profit = bcadd($profit,$val['profit'],4);
                    }
                    MywalletLog::addLog($v['id'],$profit,4,'团队奖',12,1);
                }
            }
            return $list;
    }

    #获取团队
    static public function getTeamProfit($data, $id,$level,$percentage,$peers){
        $list = array();
        foreach($data as $v) {
            if($v['pid'] == $id) {
                if ($v['team_level'] < $level) {
                    //团队奖
                    $v['percen'] = $percentage;
                    $v['profit'] = bcmul($v['total'],bcmul($percentage,0.01,8),4);
                    $item = self::getTeamProfit($data, $v['id'],$level,$percentage,$peers);
                    array_push($list, $v);
                    if (!empty($item)) {
                        $list = array_merge($list, $item);
                    }
                }else{
                    if ($v['team_level'] == $level) {
                        $v['percen'] = $peers;
                        $v['profit'] = bcmul($v['total'],bcmul($peers,0.01,8),4);
                        array_push($list, $v);
                        //平级奖
                    }
                }
            }
        }
        return $list;
    }

    /**
     * [增加个人业绩]
     * @param
     * @return
     */
    public static function addselfperformance( $uid , $number = 0 ){
        $user = User::where('id',$uid)->find()->toArray();
        if(!$user) return '会员不存在';
        // 增加个人业绩
        User::where('id',$uid)->setInc('selfperformance',$number);
        User::where('id',$uid)->setInc('performance',$number);
        return '完成';
    }

    /**
     * [增加团队业绩/增加每月团队业绩]
     * 发货时增加业绩
     * @param
     * @return
     */
    public static function addteamperformance( $pid , $number = 0 ){
        $user = User::field('id,pid,mathteamperformancetime')->where('id',$pid)->find()->toArray();
        if(!$user) return '会员不存在';
        self::mathteamperformancetime($user);// 当月没有计算过团队业绩，清零重新开始
        // 增加团队业绩
        // User::where('id',$pid)->setInc('teamperformance',$number);
        /*所有业绩都已当月业绩为准*/
        User::where('id',$pid)->setInc('mathteamperformance',$number);
        if($user['pid'] == 0) return true;
        return self::addteamperformance($user['pid'],$number);
    }

    /**
     * [本月是否已经计算过-没有计算过，则本月月累计业绩清零]
     * @param
     * @return
     */
    public static function mathteamperformancetime($user){
        $beginThismonth = mktime(1, 0, 0, date('m'), 1, date('Y'));// 一点钟才开始计算-1号需要计算等级
        if($user['mathteamperformancetime'] < $beginThismonth){
            // 当月没有计算过团队业绩，清零重新开始
            User::where('id',$user['id'])->update(['mathteamperformance'=>0,'mathteamperformancetime'=>time()+1]);
        }
        return true;
    }

    /**
     * [升级等级]
     * 【定时任务执行-按指定时间执行计算】
     * @param
     * @return
     */
    public static function level( $uid ){
        $user = self::getUser($uid);

        if(empty($user)) return '会员不存在';
        // 直推下级所有id
        $onePid = self::oneNumber($uid);
        // 直推人数
        $oneCount = count($onePid);
        //团队的所有人数
        $teamList = self::teamCount($uid);
        $teamnumber = $teamList['number'];

        $teamLevel = self::teamLevel($user,$oneCount,$teamnumber);//团长
        $agentLevel = self::agentLevel($user,$oneCount,$teamnumber,$teamList['id']);//代理商
        $houseLevel = self::houseLevel($user,$oneCount,$teamnumber,$teamList['id']);//房主
        //return [$teamLevel,$agentLevel,$houseLevel];


        if($user['pid'] == 0) return true;
        // 查看上级是否能够升级-每个会员都计算
        return self::level($user['pid']);// 2021-1-15改（购买就升级）
    }

    /**
     * [获取审核状态]
     * @param
     * @return
     */
    public static function userLelveIndex( $user ){
        $onePid = self::oneNumber($user['id']);
        // 直推人数
        $oneCount = count($onePid);
        //团队的所有人数
        $teamList = self::teamCount($user['id']);
        $teamnumber = $teamList['number'];

        $teamLevel = self::teamLevel($user,$oneCount,$teamnumber);//团长
        $agentLevel = self::agentLevel($user,$oneCount,$teamnumber,$teamList['id']);//代理商
        $houseLevel = self::houseLevel($user,$oneCount,$teamnumber,$teamList['id']);//房主

    }
    /**
     * [团长等级]
     * @param $user 会员信息（团队业绩、月业绩、本人业绩等）
     * @param $oneCount 会员直推人数
     * @param $teamNumber 团队人数
     * @return
     */
    public static function teamLevel( $user ,$oneCount = 0 ,$teamNumber = 0){
        // 大于本人目前的等级
        $teamLevel = UserTeamLevelModel::field('id,direct,team,selfperformance,teamperformance')
                ->where('id','>',$user['team_level'])
                ->select()->toArray();
        if(empty($teamLevel)) return '已经是最高等级';
        foreach ($teamLevel as $key => $value) {
            //'直推人数不足' 团队人数不足 个人业绩不足 团队业绩不足
            $arr = [$oneCount , $value['direct'] , $teamNumber , $value['team'] , $user['selfperformance'] , $value['selfperformance'] ,  $user['mathteamperformance'] , $value['teamperformance']];
            if($oneCount < $value['direct'] || $teamNumber < $value['team'] || $user['selfperformance'] < $value['selfperformance'] ||  $user['mathteamperformance'] < $value['teamperformance'] ){
                break ;
            }
            // 升级团长等级
            User::where('id',$user['id'])->setField('team_level',$value['id']);
            return [[$oneCount < $value['direct'] ],[ $teamNumber < $value['team'] ],[ $user['selfperformance'] < $value['selfperformance'] ],[  $user['mathteamperformance'] < $value['teamperformance']]];
        }
        return $arr;
    }
    /**
     * [代理商等级]
     * @param $user 会员信息（团队业绩、月业绩、本人业绩等）
     * @param $oneCount 会员直推人数
     * @param $teamNumber 团队人数
     * * @param $teamid 团队会员id
     * @return
     */
    public static function agentLevel( $user ,$oneCount = 0 ,$teamNumber = 0,$teamid){

        // 大于本人目前的等级
        $teamLevel = UserAgentLevelModel::field('id,name,direct,team,selfperformance,teamperformance,teamlevelid,teamnumber')
            ->where('id','>',$user['agent_level'])
            ->select()->toArray();
        if(empty($teamLevel)) return '已经是最高等级';

        foreach ($teamLevel as $key => $value) {
            //'直推人数不足' 团队人数不足 个人业绩不足 团队当月业绩不足
            
            if($oneCount < $value['direct'] || $teamNumber < $value['team'] || $user['selfperformance'] < $value['selfperformance'] ||  $user['mathteamperformance'] < $value['teamperformance'] ){
                break ;
            }
            if($value['teamlevelid'] > 0){
                // 下级需要团长等级
                // 对应团长人数
                $teamLevelNumber = User::where('id','in',$teamid)->where('team_level',$value['teamlevelid'])->count();
                if($teamLevelNumber < $value['teamnumber']) break;// 团长人数不足
            }
            $agent_over_time = time() + Config::getValue('agent_time') *86400;
            // 升级代理商等级
            $data = ['agent_level'=>$value['id']];
            if($agent_over_time > $user['agent_over_time']){
                // 最新的时间比原来的长-已长的时间为准
                $data['agent_over_time'] = $agent_over_time;
            }
            User::where('id',$user['id'])->setField($data);
        }
        return true;
    }

    /**
     * [房主等级]
     * @param $user 会员信息（团队业绩、月业绩、本人业绩等）
     * @param $oneCount 会员直推人数
     * @param $teamNumber 团队人数
     * * @param $teamid 团队会员id
     * @return
     */
    public static function houseLevel( $user ,$oneCount = 0 ,$teamNumber = 0,$teamid){
        // 大于本人目前的等级
        $teamLevel = UserHouseLevelModel::field('id,direct,team,selfperformance,teamperformance,teamlevelid,teamnumber')
            ->where('id','>',$user['house_level'])
            ->select()->toArray();
        if(empty($teamLevel)) return '已经是最高等级';
        foreach ($teamLevel as $key => $value) {
            //'直推人数不足' 团队人数不足 个人业绩不足 团队业绩不足
            if($oneCount < $value['direct'] || $teamNumber < $value['team'] || $user['selfperformance'] < $value['selfperformance'] ||  $user['mathteamperformance'] < $value['teamperformance'] ){
                break ;
            }
            if($value['teamlevelid'] > 0){
                // 下级需要团长等级
                // 对应团长人数
                $teamLevelNumber = User::where('id','in',$teamid)->where('team_level',$value['teamlevelid'])->count();
                if($teamLevelNumber < $value['teamnumber']) break;// 团长人数不足
            }
            // 升级房主等级
            User::where('id',$user['id'])->setField('house_level',$value['id']);
        }
        return true;
    }

    /**
     * [当前会员信息]
     * @param
     * @return
     */
    public static function getUser($uid,$field='*'){
        if($field == '*'){
            // 会员id 上级id 个人业绩 团队业绩 本月团队业绩 团长等级 代理等级 房主等级
            $field = 'id,pid,selfperformance,teamperformance,mathteamperformance,mathteamperformancetime,team_level,agent_level,house_level,province,city,area,signbless,agent_over_time';
        }
        return User::where('id',$uid)->field($field)->find()->toArray();
    }

    /**
     * [直推会员信息]
     * @param
     * @return
     */
    public static function oneNumber($uid){
        // 直推
        $my_user = User::where('pid',$uid)->column('id');
        if(!$my_user) return [];
        return $my_user;
    }
    /**
     * [团队人数]
     * @param
     * @return
     */
    public static function teamCount( $pid ,$list = ['id'=>[],'number'=>0],$number=1){
        $userListPid = User::where('pid','in',$pid)->column('id');
        if(empty($userListPid)) return $list;
        // 累计人数
        $list['number'] += count($userListPid);
        $list['id'] = array_merge($list['id'],$userListPid);
        $list[$number] = $userListPid;
        $number++;
        return self::teamCount($userListPid,$list,$number);
    }
}